import configparser
import os
import platform
import sys
import time
import lib.random

# 设置环境变量(开发配置，实际上你不应该在代码中设置环境变量，而是通过外部配置来设置)
# 详情参考文档#配置环境变量
os.environ['MYSQL_HOST'] = 'localhost'
os.environ['MYSQL_USER'] = 'root'
os.environ['MYSQL_ROOT_PASSWORD'] = '123456'
os.environ['MYSQL_PORT'] = '3306'

# 读取并检查环境变量是否存在
def get_env_variable(var_name):
    value = os.getenv(var_name)
    if value is None:
        raise EnvironmentError(f"环境变量缺失: '{var_name}' is not set.")
    return value



dev = "1"

script_dir = os.path.dirname(os.path.abspath(__file__))
# 标志文件路径
check_file = os.path.join(script_dir, "data/config.ini")
# 获取 Python 版本
target_version = (3, 8, 1)

# 获取当前 Python 版本
current_version = sys.version_info[:3]
# 获取系统版本
system_version = platform.system()



def is_installed():
    """检查是否已经安装"""
    return os.path.exists(check_file)
def init():
    try:
        os.makedirs(os.path.dirname(check_file), exist_ok=True)
    except:
        print("创建文件夹失败！请检查该目录下权限配置：" + check_file)
    config = configparser.ConfigParser()
    host = get_env_variable('MYSQL_HOST')
    port = get_env_variable('MYSQL_PORT')
    user = get_env_variable('MYSQL_USER')
    password = get_env_variable('MYSQL_ROOT_PASSWORD')
    config['MySQL'] = {
        'host': host,
        'port': port,
        'user': user,
        'password': password
    }
    with open(check_file, 'w') as configfile:
        config.write(configfile)
def perform_installation():
    """执行安装操作"""
    # 你的安装逻辑，如安装软件包、配置文件等
    print("正在安装...")
    time.sleep(0.5)
    if current_version >= target_version:
        if system_version == "Linux":
            init()
        elif system_version == "Windows":
            if dev == "1":
                init()
            else:
                raise Exception('暂未适配Windows平台！')
        else:
            raise Exception('不受支持的操作系统!' + system_version)
    else:
        raise Exception(f"当前 Python 版本 {current_version} 过低,必须>=3.8.1")

def create_database():
    try:
        import lib.connect
        cursor = lib.connect.conn.cursor()
        system_user = 'QMySQL'
        system_user_password = lib.random.generate_random_password(16)
        create_user_sql = f"CREATE USER '{system_user}'@'%' IDENTIFIED BY '{system_user_password}';"
        cursor.execute(create_user_sql)
        # 赋予权限
        grant_sql = f"GRANT ALL PRIVILEGES ON *.* TO '{system_user}'@'%' IDENTIFIED BY '{system_user}' WITH GRANT OPTION;"
        cursor.execute(grant_sql)
        # 提交更改
        lib.connect.conn.commit()
        # 添加新的 section
        config = configparser.ConfigParser
        config.add_section('System')
        config.set('System', 'system_user', system_user)
        config.set('System', 'system_user_pw', system_user_password)
        with open(check_file, 'w') as configfile:
            config.write(configfile)


    except Exception as e:
        raise Exception("Error,在初始化时发送错误:" + e)


def main():
    if is_installed():
        print("已经安装，跳过安装步骤。")
    else:
        init()
        create_database()

if __name__ == '__main__':
    main()
